from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.mixins import ListModelMixin,CreateModelMixin,UpdateModelMixin
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .serializers import AddressTitleSerializer,AddressSerializer,EmailSerializer,CreateUserSerializer,UserDetailSerializer
from .models import User
from rest_framework.generics import RetrieveAPIView
from rest_framework.generics import UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
# Create your views here.


# 用户名
class RegisterUsernameCountAPIView(APIView):
    '''获取请求
    GET  /user.usernames/(?P<username>\w{5,20}/count/
    '''

    def get(self,request,username):

        count = User.objects.filter(username=username).count()
        context = {
            'count': count,
            'username': username
        }

        return Response(context)



# 手机号

class RegisterMobileView(APIView):
    # 请求方式： GET / users / phones / (?P < mobile > 1[345789]\d{9}) / count /

    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        context = {
            'count':count,
            'mobile':mobile
        }

        return Response(context)



# 注册
class CreateUserView(CreateAPIView):

    serializer_class = CreateUserSerializer



class UserDetailView(RetrieveAPIView):
    """
    获取登录用户的信息
    GET /users/
    既然是登录用户,我们就要用到权限管理
    在类视图对象中也保存了请求对象request
    request对象的user属性是通过认证检验之后的请求用户对象
    """
    permission_classes = [IsAuthenticated]

    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user

# 发送验证邮件
class EmailView(UpdateAPIView):
    """

    1. 当用户点击确定按钮的时候,把 邮箱发送给后台,邮箱需要校验
    2. 更新 用户的 邮箱信息
    3. 发送一个激活邮件(链接)
    4. 激活链接应该如何实现发送
    5. 邮件如何发送(代码怎么实现)
    6. 邮件采用celery异步发送

    """

    permission_classes = [IsAuthenticated]

    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user

# 验证激活邮箱
class VerificationEmailView(APIView):
    """
       验证激活邮箱
       GET /users/emails/verification/?token=xxxx

       思路:
       获取token,并判断
       获取 token中的id
       查询用户,并判断是否存在
       修改状态
       返回响应
       """
    def get(self,request):

        # 获取token, 并判断
        token = request.query_params.get('token')
        if token is None:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        # 获取token中的id,email
        # 查询用户, 并判断是否存在
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            # 修改状态
            user.email_active = True
            user.save()
            # 返回响应
            return Response({'message': 'ok'})

# 增加地址

class AddressViewSet(ListModelMixin,CreateModelMixin,UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    # 添加用户权限
    permission_classes = [IsAuthenticated]
    # 由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        '''
        保存用户地址数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''

        count = request.user.addresses.count()

        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)
        return super().create(request,*args,**kwargs)


# 用户浏览记录
# 后端接口设计


from rest_framework import mixins
from rest_framework.generics import GenericAPIView
from .serializers import SKUSerializer,AddUserBrowsingHistorySerializer
from rest_framework.permissions import IsAuthenticated
from goods.models import SKU



class UserBrowsingHistoryView(mixins.CreateModelMixin, GenericAPIView):
    """
    用户浏览历史记录
    POST /users/browerhistories/
    GET  /users/browerhistories/
    数据只需要保存到redis中
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    # 请求方式：POST /users/browerhistories/
    def post(self, request):
        """
        保存
        """
        return self.create(request)

    def get(self, request):
        """
         1.必须是登录用户
         2.根据指定用户获取指定的redis数据
         3. 通过序列化器 对数据进行 序列化操作
         4.返回数据
        """

        user = request.user

        redis_conn = get_redis_connection('history')

        sku_ids = redis_conn.lrange('history_%s' % user.id, 0, 5)
        # [1,2,3,4,5]

        skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)

            skus.append(sku)

        # 3.通过序列化器对数据进行序列化操作
        serializer = SKUSerializer(skus, many=True)
        # 4.返回数据
        return Response(serializer.data)